import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FindProducts {
	public static Boolean exists = false;
	public static ArrayList<Product> productList = new ArrayList<Product>();

	public FindProducts() throws Exception{		
	}


	public static void main(String[] args) throws Exception{

		addProducts("milk");

	}

	public static Product addProducts(String item)  throws Exception {

		//@SuppressWarnings("resource")
System.out.println("working");

		productList.clear();
		
		item = item.replaceAll("\\s+", "%20");
		
		URL oracle = new URL("http://www.tesco.ie/groceries/product/search/default.aspx?searchBox="+item);
		BufferedReader in = new BufferedReader(
				new InputStreamReader(oracle.openStream()));

		String inputLine;
		String name, price; 
		int productArrayNumber = 0;

		String nameFinder = "name:\"([\\w{1,15} ]*)"; 
		String priceFinder = "price:(\\d{1,3}.\\d{2})";
		while ((inputLine = in.readLine()) != null){
			Pattern namePattern = Pattern.compile(nameFinder);        	
			Matcher nameMatcher = namePattern.matcher(inputLine);
			Pattern pricePattern = Pattern.compile(priceFinder);
			Matcher priceMatcher = pricePattern.matcher(inputLine);

			while(nameMatcher.find()){
				exists = false;
				name = nameMatcher.group(1);
				for(int i = 0; i < productList.size();i++)
				{
					Product productExists = productList.get(i);
					if(productExists.getProductName().equals(name))
					{
						exists = true;
					}                		
				}
				if(exists== false)
				{
					Product productNew =new Product(name,null);
					productList.add(productNew);
				}

			}
			while(priceMatcher.find() && productArrayNumber<productList.size()){
				price = priceMatcher.group(1);    
				Product	productEdit = (Product) productList.get(productArrayNumber);
				productEdit.setProductPrice(price);  	
				productList.set(productArrayNumber, productEdit);  		
				productArrayNumber++;
			}
		}
		Product cheapest = null;
		if(productList.size() != 0)
		{

			cheapest = productList.get(0);
			for (int a = 0; a < productList.size()-1; a++)
			{
				Double chpPrice = Double.parseDouble(cheapest.getProductPrice());
				Double cmpPrice = 500.0;
				if(productList.get(a).getProductPrice() != null)
				{
					cmpPrice = Double.parseDouble(productList.get(a).getProductPrice());
					if(chpPrice > cmpPrice)
					{
						cheapest = productList.get(a);
					}
				}
			} 
			in.close();
		}
		return cheapest;
	}
}
